package sg.ImageShack.commands
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.utils.Dictionary;
	
	import org.httpclient.events.HttpDataEvent;
	import org.httpclient.events.HttpErrorEvent;
	import org.httpclient.events.HttpResponseEvent;
	
	import sg.ImageShack.UploadedImageDTO;
	import sg.ImageShack.components.AlertNotificationWindow;
	import sg.ImageShack.components.UploadProgressWindow;
	import sg.ImageShack.components.UploadResultWindow;
	import sg.ImageShack.events.BackendEvent;
	import sg.ImageShack.models.AppContext;

	public class BackendCommand implements ICommand
	{
		public var ctx : AppContext;
		private var resultDict : Dictionary = new Dictionary();
		private var _result : String;
		
		public function execute(event:CairngormEvent):void
		{
			switch (event.type)
			{
					case BackendEvent.UPLOAD_IMAGE: onUploadImage(event as BackendEvent); break;
				case BackendEvent.CANCEL_UPLOADING: removeEvents(); break;
									   default: break;
			}
		}
		private function onCancelUploading(event : BackendEvent):void
		{
			removeEvents();
		}
		private function onUploadImage(event : BackendEvent):void
		{
			_result = "";
			ctx.uploadedImages.removeAll();
			ctx.checkNotClosedWindows();
			for each (var _file : File in event.dropFiles)
			{
				if (!ctx.getContentType(_file.type))
				{
					AlertNotificationWindow.showAlert(_file.name + " : wrong file type. Please select another image.");
					return;
				}
				if (_file.size > 130000000)
				{
					AlertNotificationWindow.showAlert(_file.name + " : file to big (>1.3M). Please select another image.");
					return;
				}
			}	
			
			var file : File = event.dropFiles.getItemAt(0) as File;
			ctx.currentFileToUpload = file;
				
			ctx.httpClient.addEventListener(HttpDataEvent.DATA, onHttpDataHandler);
			ctx.httpClient.addEventListener(HttpResponseEvent.COMPLETE, onHttpResponceComplete);
			ctx.httpClient.addEventListener(HttpErrorEvent.TIMEOUT_ERROR, onTimeOutError);
			
			UploadProgressWindow.showProgressWindow();
			ctx.httpClient.postMultipart(ctx.uri, ctx.addFilePart(file));
		}
		private function onHttpDataHandler(event : HttpDataEvent):void
		{
			_result += event.readUTFBytes();
		}
		private function onHttpResponceComplete(event : HttpResponseEvent):void
		{
			removeEvents();
			var xml : XML = new XML(_result);
			
			var img : UploadedImageDTO = new UploadedImageDTO;
			img.imageLink = xml.elements(ctx.linksQName)[0].elements(ctx.imageLinkQName)[0].toString();
			var _thumb : XMLList = xml.elements(ctx.linksQName)[0].elements(ctx.thumbLinkQName)
			if (_thumb.length() != 0)
			{
				img.thumbLink = xml.elements(ctx.linksQName)[0].elements(ctx.thumbLinkQName)[0].toString();
			} else {
				img.thumbLink = img.imageLink;
			}
			img.resolutionHeight = xml.elements(ctx.resolutionQName)[0].elements(ctx.heightQName)[0].toString();
			img.resolutionWidth = xml.elements(ctx.resolutionQName)[0].elements(ctx.widthQName)[0].toString();
			
			ctx.uploadedImages.addItem(img);
			ctx.saveHistory(ctx.uploadedImages);
			
			UploadProgressWindow.closeProgressWindow();
			UploadResultWindow.showUploadedResult();
		}
		private function onTimeOutError(event : HttpErrorEvent):void
		{
			removeEvents();
			UploadProgressWindow.closeProgressWindow();
			AlertNotificationWindow.showAlert("The server did not responce. Please try again.", true, true);
		}
		private function removeEvents():void
		{
			ctx.httpClient.removeEventListener(HttpDataEvent.DATA, onHttpDataHandler);
			ctx.httpClient.removeEventListener(HttpResponseEvent.COMPLETE, onHttpResponceComplete);
			ctx.httpClient.removeEventListener(HttpErrorEvent.TIMEOUT_ERROR, onTimeOutError);
		}
	}
}